<template>
  <tl-sub-page :render="render" :with-header="false" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-drawer" :size="size" @open="open" @close="close" :destroy-on-close="true" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true">
    <div class="project-container">
      <div class="customer-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_plan_edit.png" class="logo" style="width: 55px;height: 55px">
          <div class="content" :title="model.projectname">
            <p>
              <b>{{ projectinfo.projectname }}</b>
            </p>
            <p class="light">
              <span>项目经理：{{ projectinfo.projectmanager }}</span>
              <span>创建时间：{{ formatDate(projectinfo.createon) }}</span>
            </p>
          </div>
        </div>
        <div class="toolbar" style="float:right;margin-bottom:6px">
          <el-button @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="isshowedit" icon="el-icon-document-checked" type="text" size="medium">保存
          </el-button>
          <tl-attachment ref="attachmentRef" sourceType="GpmProjectPlan" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
            <el-button type="text" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()" size="medium">{{this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : ''}}
              [{{ this.$refs.attachmentRef ? ( this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount ) : 0 }}]
            </el-button>
          </tl-attachment>
          <el-button type="text" @click.native="openChangeHistoryDialog('historyList')" v-if="model.id && model.version>1">修改历史</el-button>
          <el-button @click="$refs.history.visible = true" :disabled="disableApprovalHistory" type="text" size="medium">
            <svg-icon icon-class="list" />审批历史
          </el-button>
          <el-button type="danger" style="float: right" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="project-nav" :style="{ height: mainHeight + 'px' }">
        <ul class="nav-list" style="top:0px">
          <template v-for="(item, index) in navList">
            <li :key="item.code" v-if="model.id || item.show || index === 0" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 100px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <!-- <el-row v-if="fromApproval === '1'">
      <el-col :span="24">
      </el-col>
    </el-row> -->
      <div class="project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="customer-main-container" id="customerMainContainer">
          <div style="padding:0 10px">
            <a id="baseinfo" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                基本信息
              </div>
              <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="isshowedit">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="变更原因" prop="changereason" v-if="displayChangeReasonFlag">
                      <el-input type="textarea" show-word-limit maxlength="1000" :rows="4" v-model="model.changereason"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="策划书名称" prop="proposalname" :rules="rules.validateRequire">
                      <el-input v-model="model.proposalname" :disabled="true"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- <el-row>
                  <el-col :span="24">
                    <el-form-item label="策划书描述" prop="plandescription" :rules="rules.validateRequire">
                      <el-input v-model="model.plandescription" type="textarea" :rows="4" maxlength="800" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                </el-row> -->
              </el-form>
            </div>
            <a id="background" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                背景策略
              </div>
              <el-form class="tl-form" ref="form1" :model="model" :rules="rules" label-width="150px" :disabled="isshowedit">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目背景" prop="projectbackground" :rules="rules.validateRequire">
                      <el-input v-model="model.projectbackground" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述项目背景，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目目标和策略" prop="projecttarget" :rules="rules.validateRequire">
                      <el-input v-model="model.projecttarget" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述目标策略，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <a id="implementation" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                项目实施方案
              </div>
              <el-form class="tl-form" ref="form2" :model="model" :rules="rules" label-width="150px" :disabled="isshowedit">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目实施方案" prop="projectimplementation" :rules="rules.validateRequire">
                      <el-input v-model="model.projectimplementation" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述项目实施方案，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <a id="milepost" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                里程碑
              </div>
              <el-form class="tl-form" ref="form5" :model="model" :rules="rules" label-width="150px">
                <tl-line ref="line" :parentId="model.id" :editable="!disableSave" :isshowdisable="isshowedit" :projectinfo="projectinfo" :planstate="model.state"></tl-line>
              </el-form>
            </div>
            <a id="docapplyinfo" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                单据申请信息
              </div>
              <el-form class="tl-form" ref="form6" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="申请部门" prop="applydeptname">
                      <tl-ref-dept v-model="model.applydeptcode" :initDisplayData.sync="model.applydeptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请公司" prop="applyorgname">
                      <el-input v-model="model.applyorgname" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="申请人姓名" prop="applyusername">
                      <tl-ref-user v-model="model.applyusername" :initDisplayData.sync="model.applyusername" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请人工号" prop="applyusercode">
                      <el-input v-model="model.applyusercode" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="单据日期" prop="docdate">
                      <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="提交时间" prop="submitdate">
                      <el-date-picker v-model="model.submitdate" type="date" placeholder="提交时间" value-format="yyyy-MM-dd" disabled></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="审批流程" prop="flowid">
                      <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="状态" prop="state">
                      <el-input v-model="model.dispstate" disabled></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <tl-approval-history ref="history" sourceType="GpmProjectPlan" :sourceId="model.id" />
          </div>
        </el-scrollbar>
      </div>
    </div>
    <change-log-history ref="historyList" topSourceType="GpmProjectPlan" :topSourceId="model.id + ''"></change-log-history>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlLine from '../gpmProjectMilepost/indexFrame'
import changeLogHistory from "../gpmProject/component/changeLogHistory"
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { formatDate } from '@tapui/utils/date'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlLine, changeLogHistory },
  data() {
    return {
      moduleTitle: '项目策划',
      urlPrefix: '/sd/projectPlan/',
      url: {
        // 额外的url
        projectLoadInfo: '/sd/projectPlan/projectLoadInfo'
      },
      activeTabName: 'basic',
      isRefreshLine: false,
      count: 0,
      planInfo: {},
      navList: [
        { name: '基本信息', count: 0, flag: null, on: true, code: 'baseinfo', show: true },
        { name: '背景策略', count: 0, flag: null, on: true, code: 'background', show: true },
        { name: '项目实施方案', count: 0, flag: null, on: true, code: 'implementation', show: true },
        { name: '里程碑', count: 0, flag: null, on: true, code: 'milepost', show: true },
        { name: '单据申请信息', count: 0, flag: null, on: true, code: 'docapplyinfo', show: true }
      ],
      fromApproval: '',
      size: '95%',
      mainHeight: 100,
      projectinfo: {},
      isshowedit: true,
      displayChangeReasonFlag: false
    }
  },
  props: {
    render: {
      default: 'el-drawer',
      type: String
    },
    oldmilepost: []
  },
  methods: {
    saveInfo(resolve, reject) {
      this.$refs.line.updatemilepostBatch()
      putAction(this.url.edit, this.model)
        .then(res => {
          if (res.success) {
            this.$emit('refresh')
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch(err => {
          this.$tap.alert('修改信息失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    projectLoadInfo() {
      getAction(this.url.projectLoadInfo, { projectCode: this.model.projectcode }).then((res) => {
        if (res.success) {
          this.$set(this, 'projectinfo', res.result.projectinfo)
        } else {
          this.$tap.alert(res.message, "warning")
        }
      })
    },
    formatDate(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd HH:mm')
    },
    // 点击左侧导航
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 250
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {
      const scrollFun = () => {
        const currentEl = [...this.$el.getElementsByClassName('step-position')].find((item) => item.getBoundingClientRect().y >= 0)
        const code = currentEl ? currentEl.id : ''
        this.navList.forEach((m) => (m.on = m.code === code))
      }
      this.mainScrollElement.removeEventListener('scroll', scrollFun)
      this.mainScrollElement.addEventListener('scroll', scrollFun)
    },
    created() {
      window.addEventListener('resize', this.resizeHandler)
    },
    checkplancount() {
      let param = {}
      if (this.isAdd) {
        param = {
          projectcode: this.model.projectcode,
          isadd: this.isAdd
        }
      } else {
        param = {
          projectcode: this.model.projectcode,
          isadd: this.isAdd,
          id: this.model.id
        }
      }
      getAction('/sd/projectPlan/checkplancount', param).then((res) => {
        if (res.success) {
          this.displayChangeReasonFlag = !res.result.isFirstPlan
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    open() {
      this.navList.forEach(function(item, index) {
        if (index === 0) {
          item.on = true
        } else {
          item.on = false
        }
      })
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          // this.loadData()
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then(_ => {
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
            if (this.$refs.line) {
              this.$refs.line.milepostLoadInfo()
            }
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
            if (this.$refs.line) {
              this.$refs.line.milepostLoadInfo()
            }
          })
        }
      })
      this.$nextTick(() => {
        this.mainScrollElement = this.$el.querySelector('#customerMainContainer .el-scrollbar__wrap')
        this.onMainScroll()
      })
    },
    close() {
      this.displayChangeReasonFlag = false
      this.model = {}
    },
    loaded() {
      // 页面加载完毕执行
      const approvalparam = this.$parent.$parent.$parent.nodeModel.approvalparam
      const approvalparamobject = JSON.parse(approvalparam)
      if (approvalparamobject !== null) {
        if (approvalparamobject.hasOwnProperty('isEdit')) {
          this.isshowedit = false
        }
      } else {
        this.isshowedit = true
      }
      this.isRefreshLine = false
      this.$refs.form.clearValidate()
      this.$refs.form1.clearValidate()
      this.$refs.form2.clearValidate()
      this.projectLoadInfo()
      this.checkplancount()
    },
    tabClick(tab) {
      if (tab.name === 'line') {
        if (!this.model.id) {
          this.$nextTick((_) => {
            this.activeTabName = 'basic'
          })
          this.$tap
            .confirm('当前数据未保存，是否立即保存数据？')
            .then((_) => {
              this.doSubmitEdit()
            })
            .catch((_) => { })
        } else if (!this.isRefreshLine) {
          this.$refs.line.doQuery()
          this.isRefreshLine = true
        }
        this.$refs.line.initPage()
      }
    },
    beforeApproval() {
      if (this.$refs.attachmentRef.fileList.length === 0) {
        this.$tap.alert('请上传策划书附件！', 'warning')
        this.submitLoading = false
        return false
      }
      return true
    },
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    openChangeHistoryDialog(historyList) {
      /** 打开详情对话框实现*/
      this.$refs[historyList].visible = true
    }
  }
}
</script>
<style scoped lang="scss">
/deep/.el-drawer {
  padding: 0 15px;
}
/deep/ .el-drawer__body {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  overflow: auto;
  border-top: 1px solid rgb(232, 232, 232);
}
</style>
